/*
 * This files defines the client
 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> 
#include <netdb.h>
#include <termios.h>
#include "Player_manager.c"
#include <ctype.h>

#define PORT 54321
#define MAXDATASIZE
#define DEBUG 0
#define ADDRESS "127.0.0.1"
//terminal variables
int fd, client_socket;
struct termios old_settings, new_settings;
int send_auth(char* user_name, char* password);

int main(int argc, char *argv[])
{
	struct sockaddr_in their_addr;
	their_addr.sin_family = PF_INET;
	their_addr.sin_addr.s_addr =  inet_addr(ADDRESS);
	their_addr.sin_port = htons(PORT);
	bzero((&their_addr.sin_zero),8);
	int keep_running = 1;
	char user_name[100];
	char password[100];
	while(keep_running>0)
	{
		if ((client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) <0)
		{
			printf("socket() failed");
			exit(1);
		}
		
		//get auth
		
		printf("Enter user name or enter q to quit:\n");
		fflush(stdin);
		fgets(user_name,100,stdin);
		if((strlen(user_name) == 2) && ((user_name[0]=='q')||(user_name[0]=='Q')))
		{
			keep_running = -1;
			close(client_socket);
			return(0);
		}
		printf("Enter pass word:\n");
		//disable text echoing on the terminal
		fd = fileno(stdin);
		tcgetattr(fd,&old_settings);
		new_settings = old_settings;
		new_settings.c_lflag &= ~ECHO;
		tcsetattr(fd,TCSANOW,&new_settings);
		fgets(password,100,stdin);
		tcsetattr(fd,TCSANOW,&old_settings);
		fflush(stdin);
		//make sure buffer is empty
		if (connect(client_socket,(struct sockaddr*) &their_addr, sizeof(struct sockaddr)) == -1)
		{
			printf("connect failed");
			exit(1);
		}
		//send auth
		int response = send_auth(user_name,password);
		if(response!=1)
		{
			
				printf("Invalid User name/password\n");
				close(client_socket);
				char cont[10];
				printf("Retry y/n/q?\n");;
				fgets(cont,10,stdin);
				if(DEBUG)printf("cont:%s\n",cont);
				if (cont[0] == 'n'||cont[0] == 'N')
				{
					return(0);
				}else if(cont[0] == 'y'||cont[0] == 'Y')
				{
					continue;
				}else if(cont[0] == 'q'||cont[0] == 'Q')
				{
					return(0);
				}else
				{
				  printf("Bad Input quiting\n");
				  return(1);
				}
		}
		keep_running = -1;
		printf("Welcome %s Please enter a query:\n",user_name);
		
	}
	//enter query
	int query_more=1;
	while(query_more>0)
	{
		if(query_more>1)
		{
			//re socket
			if ((client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) <0)
			{
				printf("socket() failed");
				exit(1);
			}
			//reconnect
			if (connect(client_socket,(struct sockaddr*) &their_addr, sizeof(struct sockaddr)) == -1)
			{
				printf("connect failed");
				exit(1);
			}
			//re authorize
			int response;
			if(!(response = send_auth(user_name,password)))
			{
				printf("Authenication failure restart the program\n");
				return 0;
			}
			printf("Please enter a query\n");
		}
		fflush(stdin);
		char query_in[100];
		fgets(query_in, 100, stdin);
		
		
		//send query
		if((send(client_socket,query_in,strlen(query_in),0))!=strlen(query_in))
		{
			printf("send() sent different number of bytes\n");
			exit(1);
		}
		//get response
		int success = -1;
		if((recv(client_socket,&success,sizeof(int),0)) != sizeof(int))
		{
			printf("failed to recieve success notification\nQuiting\n");
			exit(1);
			
		}
		if(success!=1)
		{
			printf("Name not In Database\n");
			close(client_socket);
			char cont[10];
			printf("Send a new query y/n/q?\n");
			fgets(cont,10,stdin);
			if(DEBUG)printf("cont q:%s\n",cont);
			if (cont[0] == 'n'||cont[0] == 'N')
			{
				return(0);
			}else if(cont[0] == 'y'||cont[0] == 'Y')
			{
				query_more++;
				continue;
			}else if(cont[0] == 'q'||cont[0] == 'Q')
			{
				return(0);
			}else
			{
			  printf("Bad Input quiting\n");
			  return(1);
			}
		}
		struct cricket_player p;
		if((recv(client_socket,&p,sizeof(struct cricket_player),0)) <0)
		{
			printf("recive failed\n");
			exit(1);
			
		}
		//print information
		printf("\"%s\" Scored a total of %d runs\n",p.name,p.runs);
		printf("More Player information for %s:\n",p.name);
		printf("\tCountry: \t%s\n",p.country);
		printf("\tAverage: \t%3.3f\n",p.batting_average);
		printf("\tHigh Score:\t%d\n",p.highest_score);
		printf("\t\"%s\" has been queried %d times in total\n",p.name,p.access_count);
		close(client_socket);
		char cont[10];
		//check if new query
		printf("Send a new query y/n/q?\n");
		fgets(cont,10,stdin);
		if(DEBUG)printf("cont q:%s\n",cont);
		if (cont[0] == 'n'||cont[0] == 'N')
		{
			return(0);
		}else if(cont[0] == 'y'||cont[0] == 'Y')
		{
			query_more++;
			continue;
		}else if(cont[0] == 'q'||cont[0] == 'Q')
		{
			
			return(0);
		}else
		{
		  	printf("Bad Input quiting\n");
		  	return(1);
		}
		return 0;
	}
	
	
	
}
	
int send_auth(char* user_name, char* password)
{
		if((send(client_socket,user_name,strlen(user_name),0)) != strlen(user_name))
		{
		printf("send() sent different number of bytes\n");
		exit(1);
	}
	if((send(client_socket,password,strlen(password),0)) != strlen(password))
	{
		printf("send() sent different number of bytes\n");
		exit(1);
	}
	//get auth response
	int response=-1;
	if((recv(client_socket,&response,sizeof(int),0)) != sizeof(int))
	{
		printf("recive failed\n");
		exit(1);
		
	}
	return response;
}
